package com.yf.aclient;

import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;

import com.yf.aclient.activity.ExDialog;
import com.yf.aclient.activity.PictruesViewActivity;
import com.yf.aclient.adapter.PicViewAdapter;
import com.yf.aclient.notification.MyNotificationMgr;
import com.yf.aclient.threads.UploadThread;

public class MyClientActivity extends TabActivity implements
		OnTabChangeListener {
	/** Called when the activity is first created. */
	private static NotificationManager mNotificationManager;
	private Map<String, Integer> map;
	private static Random random = new Random();
//	private Button uploadPic;
	private  TabHost tabHost;

	private static final int PICK_PICTURE = 10;
    private  String  type="1";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setting=this.getSharedPreferences("globelValue",MODE_PRIVATE);
//		SharedPreferences.Editor eidtor=setting.edit();
//		eidtor.putInt("severUrl", R.string.serverUrl);
//		eidtor.commit();
		tabHost = getTabHost();
		TabHost.TabSpec pic = tabHost.newTabSpec("picTab_1");

		pic.setIndicator("图片", getResources().getDrawable(R.drawable.uploadpic));
		Intent intent = new Intent();
		intent.putExtra("type", "1");
		intent.setClass(this, PictruesViewActivity.class);
//		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		pic.setContent(intent);
		tabHost.addTab(pic);
		
		TabHost.TabSpec doc = tabHost.newTabSpec("docTab_2");

		doc.setIndicator("文档", getResources().getDrawable(R.drawable.doc));
		Intent intent1 = new Intent();
		intent1.putExtra("type", "2");
		intent1.setClass(this, PictruesViewActivity.class);
//		intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		doc.setContent(intent1);
		tabHost.addTab(doc);

		TabHost.TabSpec music = tabHost.newTabSpec("musicTab_3");
		music.setIndicator("音乐", getResources().getDrawable(R.drawable.music));
		Intent intent2 = new Intent();
		intent2.putExtra("type", "3");
		intent2.setClass(this, PictruesViewActivity.class);
		music.setContent(intent2);
		tabHost.addTab(music);

		TabHost.TabSpec video = tabHost.newTabSpec("videoId_4");
		video.setIndicator("视频", getResources().getDrawable(R.drawable.vedio));
		Intent intent3 = new Intent();
		intent3.putExtra("type", "4");
		intent3.setClass(this, PictruesViewActivity.class);
//		intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		video.setContent(intent3);
		tabHost.addTab(video);
		tabHost.setOnTabChangedListener(this);
		tabHost.setCurrentTab(0);
		
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
		// Toast.makeText(getBaseContext(), "横屏", 6000).show();
		// } else {
		// Toast.makeText(getBaseContext(), "竖屏", 6000).show();
		// }

	}

	@Override
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		type=tabId.substring(tabId.length()-1, tabId.length());
//		View  v=tabHost.getCurrentTabView();
//		ListView  list=(ListView)v.findViewById(R.id.pictruesList);
//		list 
	//	Toast.makeText(getBaseContext(), tabId, Toast.LENGTH_LONG).show();
	//	TabHost.TabSpec music = tabHost.;
	}
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.title_icon, menu);
    	return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.upload:
//                Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_SHORT).show();
            {
				Intent intent = new Intent();
				if(type.equals("1")){
					intent.putExtra("title","选择上传图片文件"
			                   );
				//	notificationId=R.string.picture_id;
				}else if(type.equals("2")){
					intent.putExtra("title","选择上传文档文件"
			                   );  
				//	notificationId=R.string.document_id;
				}else if(type.equals("3")){
					intent.putExtra("title","选择上传音乐文件"
			                   );  
				//	notificationId=R.string.music_id;
				}else{
					intent.putExtra("title","选择上传视频文件"
			                   );  
			//		notificationId=R.string.vedio_id;
				}
    // 设置文件管理器标题
		         intent.setDataAndType(Uri.fromFile(new File("/sdcard")), "*/*");      // 设置起始文件夹和文件类型
//				Intent it = new Intent(PictruesViewActivity.this,
//						SelectPicActivity.class);
		         intent.setClass(MyClientActivity.this,
						ExDialog.class);
				startActivityForResult(intent, PICK_PICTURE);
            	return true;
            }
            case R.id.cancel:
                return true;
            default:
                // Don't toast text when a submenu is clicked
                if (!item.hasSubMenu()) {
                    Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
                    return true;
                }
                break;
        }
        
        return false;
    }
    
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (requestCode == PICK_PICTURE) {
			if (resultCode == RESULT_OK) {
				// A contact was picked. Here we will just display it
				// to the user.
				// startActivity(new Intent(data));
				// String action = intent.getAction();
//				Bundle b = intent.getExtras();
//				String[] urls = (String[]) b.get("data");
////				String[] urls = (String[]) b.get("data");
//				if (urls.length < 1)
//					return;
//				Intent uploadIntent = new Intent("com.yf.aclient.uploadService");
//				uploadIntent.putExtra("data", urls);
//				uploadIntent.putExtra("type", type);
//				uploadIntent.putExtra("notificationId", type);
//				uploadIntent.putExtra("memo", b.getString("memo"));
//				// 这个服务必须手动stop;
//				startService(uploadIntent);
//			//	tabHost.getCurrentTabView();
				

				// A contact was picked. Here we will just display it
				// to the user.
				// startActivity(new Intent(data));
				// String action = intent.getAction();
				Bundle b = intent.getExtras();
				String[] urls = (String[]) b.get("data");
				String memo = b.getString("memo");
				if (urls.length < 1)
					return;
//				Intent uploadIntent = new Intent("com.yf.aclient.uploadService");
//				uploadIntent.putExtra("data", urls);
//				uploadIntent.putExtra("memo", memo);
//				// 这个服务必须手动stop;
//				startService(uploadIntent);
				int notification = random.nextInt();
				map = new HashMap<String, Integer>();
				mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
				for (String url : urls) {
					if (!url.equals("")) {
						notification++;
						UploadThread thread = new UploadThread(url,memo, type,
								getString(R.string.serverUrl), uploadhandler);
						thread.start();
						map.put(URLEncoder.encode(url), notification);
						new MyNotificationMgr(mNotificationManager, getBaseContext(),
								R.drawable.upload, "文件上传", "正在上传"+url, true, notification);
					}
				}
			
				
			}
		}

	}
	
//	/**
//	 * 
//	 * 从服务器构造数据。。。
//	 */
//	private void constructData() {
//		//SharedPreferences setting=this.getPreferences(MODE_PRIVATE);
////		String serverUrl=;
//		String getRolesUrl = getString(R.string.serverUrl)+"/task/getResouresResource.action";
//		try {
//			StringBuilder result = new StringBuilder("");
//			HttpPost request = new HttpPost(getRolesUrl);
//			// request.setParams(params);
//			StringEntity reqEntity = new StringEntity("resourceType="+type);
//			reqEntity.setContentType("application/x-www-form-urlencoded");
//			request.setEntity(reqEntity);
//			//request.set
//			
//			HttpResponse response = client.execute(request);
//			
//			// Get the response
//			BufferedReader rd = new BufferedReader(new InputStreamReader(
//					response.getEntity().getContent()));
//			String line = "";
//			while ((line = rd.readLine()) != null) {
//				result.append(line);
//			}
//			// JSONArray
//			JSONArray jsonArray = new JSONArray(result.toString());
//			result.delete(0, result.length());
//			// JSONArray.
//			if(jsonArray.length()<=0){
//				JSONObject jso=new JSONObject();
//				jso.put("id", "#");
//				myData.add(jso);
//				return;
//			}
//			for (int i = 0; i < jsonArray.length(); i++) {
//				JSONObject jso = jsonArray.getJSONObject(i);
//				jso.put("fileUrl", getString(R.string.serverUrl)+jso.getString("reourceUrl"));
//				myData.add(jso);
//			}
//		} catch (Exception e) {
//            Toast.makeText(this, "request:" + getRolesUrl + "出错！", Toast.LENGTH_LONG).show();
//            handler.sendEmptyMessage(0);
//			System.out.println("request:" + getRolesUrl + "出错！");
//		}
//	}
	/***
	 * 上传成功后，更新当前ACTIVITY
	 * 
	 */
	private Handler uploadhandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String info = (String) msg.obj;
				JSONArray  jsoarr=new JSONArray(info);
			//	String tt="{\"jso\":\"{\"id\":\"53\",\"memo\":\"uu\",\"reourceUrl\":\"/music/go.gif\",\"resourceName\":\"go.gif\",\"resourceType\":\"3\",\"sharedTimes\":\"0\",\"uploadTime\":\"1329890471022\",\"userQq\":\"305757181\"}\",\"nid\":\"%2Fsdcard%2FDownload%2Fgo.gif\"}";
				JSONObject njson = (JSONObject) jsoarr.get(0);
				JSONObject rjson=(JSONObject) jsoarr.get(1);
				Intent intent = new Intent(
						"broadcastReceiver.UploadBroadcastReceiver");
				intent.putExtra("info", rjson.getString("resourceName") + "上传成功");
				sendBroadcast(intent);
				int nid = map.get(njson.getString("nid"));
				String finish=URLDecoder.decode(njson.getString("nid"));
				new MyNotificationMgr(mNotificationManager,
						getBaseContext(), R.drawable.upload, "上传完成",
						finish+"上传完成！", true, nid);
				  ListView	listView=	(ListView)getLocalActivityManager().getCurrentActivity().findViewById(R.id.pictruesList);
//			   View  vvv=tabHost.getCurrentTabView();
//			   ListView	lv	=(ListView)tabHost.findViewById(R.id.pictruesList);
//			   View  v=tabHost.getChildAt(3);
////			   View vvv = tabWidget.getChildAt(tabHost.getCurrentTab()); 
//			   vvv.setBackgroundColor(Color.GREEN);
//				ListView	listView	=(ListView)vvv.findViewById(R.id.pictruesList);
				PicViewAdapter  adapter= (PicViewAdapter) listView.getAdapter();
				List<JSONObject> map=adapter.getmData();
				map.add(rjson);
				adapter.notifyDataSetChanged();
		//		listView.setAdapter(adapter);
//				//PictruesViewActivity prictureView=(PictruesViewActivity)tabHost.getCurrentTabView();

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	};
}